<template>
    <div>
        <div class="container">
            <div class="handle-box">
                <div>
                    <el-input v-model="query.keywords" placeholder="关键词" class="handle-input mr10"></el-input>
                    <el-select v-model="query.type" class="m-2 mr10" placeholder="请选择类型" size="large">
                        <el-option key="0" label="全部类型" value="0" />
                        <el-option v-for="bartype in barTypes" :key="bartype.dic_vlu" :label="bartype.dic_vlu"
                            :value="bartype.dic_key" />
                    </el-select>
                    <el-button type="primary" size="small" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                </div>
                <div>
                    <el-button type="primary" size="small" icon="el-icon-plus" @click="handleCreate" class="add-btn">
                        添加条码</el-button>
                </div>
            </div>
            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
                :cell-style="{padding:'3px 0'}">
                <el-table-column prop="bar_id" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="bar_val" align="center" label="条码值"></el-table-column>
                <el-table-column prop="bar_rtn1" align="center" label="返回值1"></el-table-column>
                <el-table-column prop="bar_rtn2" align="center" label="返回值2"></el-table-column>
                <el-table-column prop="bar_rtn3" align="center" label="返回值3"></el-table-column>
                <el-table-column prop="bar_rtn4" align="center" label="返回值4"></el-table-column>
                <el-table-column prop="bar_rtn5" align="center" label="返回值5"></el-table-column>
                <el-table-column prop="bar_type" label="类型" align="center">
                    <template #default="scope">{{ getAdviceType(scope.row.bar_type) }}</template>
                </el-table-column>
                <el-table-column prop="period_type" label="有效类型" align="center">
                    <template #default="scope">
                        {{getPeriodType(scope.row.period_type)}}
                    </template>
                </el-table-column>
                <el-table-column label="有效期" align="center" width="300">
                    <template #default="scope">
                        {{scope.row.period_start}}<br>{{scope.row.period_end}}
                    </template>
                </el-table-column>
                <el-table-column prop="period_num" align="center" label="有效次数"></el-table-column>
                <el-table-column label="操作" width="230" align="center">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="query.page"
                    :page-size="query.limit" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
            </div>
        </div>

        <!-- 添加弹出框 -->
        <el-dialog title="添加" v-model="addVisible" width="50%">
            <el-form label-width="110px">
                <el-form-item label="条码类型">
                    <el-radio-group v-model="createForm.bar_type" class="ml-4">
                        <el-radio v-for="item in barTypes" :label="item.dic_key" size="large">{{item.dic_vlu}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="条码值">
                    <el-input type="textarea" :rows="2" v-model="createForm.bar_val"></el-input>
                </el-form-item>
                <el-form-item label="返回值1">
                    <el-input type="textarea" :rows="2" v-model="createForm.bar_rtn1"></el-input>
                </el-form-item>
                <el-form-item label="返回值2">
                    <el-input type="textarea" :rows="2" v-model="createForm.bar_rtn2"></el-input>
                </el-form-item>
                <el-form-item label="返回值3">
                    <el-input type="textarea" :rows="2" v-model="createForm.bar_rtn3"></el-input>
                </el-form-item>
                <el-form-item label="返回值4">
                    <el-input type="textarea" :rows="2" v-model="createForm.bar_rtn4"></el-input>
                </el-form-item>
                <el-form-item label="返回值5">
                    <el-input type="textarea" :rows="2" v-model="createForm.bar_rtn5"></el-input>
                </el-form-item>
                <el-form-item label="有效期类型 ">
                    <el-radio-group v-model="createForm.period_type" class="ml-4">
                        <el-radio v-for="item in periodTypes" :label="item.id" size="large">{{item.title}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="有效日期" v-if="createForm.period_type ==2">
                    <el-date-picker class="ml10 mr10" v-model="createForm.date" type="datetimerange" unlink-panels
                        range-separator="到" start-placeholder="开始日期" end-placeholder="结束日期"
                        value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="有效次数" v-if="createForm.period_type ==3">
                    <el-input v-model="createForm.period_num"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveCreate">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" v-model="editVisible" width="50%">
            <el-form label-width="110px">
                <el-form-item label="条码类型">
                    <el-radio-group v-model="eidtForm.info.bar_type" class="ml-4">
                        <el-radio v-for="item in barTypes" :label="item.dic_key" size="large">{{item.dic_vlu}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="条码状态">
                    <el-radio-group v-model="eidtForm.info.period_state" class="ml-4">
                        <el-radio label="1" size="large">有效</el-radio>
                        <el-radio label="0" size="large">无效</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="条码值">
                    <el-input type="textarea" :rows="2" v-model="eidtForm.info.bar_val"></el-input>
                </el-form-item>
                <el-form-item label="返回值1">
                    <el-input type="textarea" :rows="2" v-model="eidtForm.info.bar_rtn1"></el-input>
                </el-form-item>
                <el-form-item label="返回值2">
                    <el-input type="textarea" :rows="2" v-model="eidtForm.info.bar_rtn2"></el-input>
                </el-form-item>
                <el-form-item label="返回值3">
                    <el-input type="textarea" :rows="2" v-model="eidtForm.info.bar_rtn3"></el-input>
                </el-form-item>
                <el-form-item label="返回值4">
                    <el-input type="textarea" :rows="2" v-model="eidtForm.info.bar_rtn4"></el-input>
                </el-form-item>
                <el-form-item label="返回值5">
                    <el-input type="textarea" :rows="2" v-model="eidtForm.info.bar_rtn5"></el-input>
                </el-form-item>
                <el-form-item label="有效期类型 ">
                    <el-radio-group v-model="eidtForm.info.period_type" class="ml-4">
                        <el-radio v-for="item in periodTypes" :label="item.id" size="large">{{item.title}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="有效日期" v-if="eidtForm.info.period_type ==2">
                    <el-date-picker class="ml10 mr10" v-model="eidtForm.info.date" type="datetimerange" unlink-panels
                        range-separator="到" start-placeholder="开始日期" end-placeholder="结束日期"
                        value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="有效次数" v-if="eidtForm.info.period_type ==3">
                    <el-input v-model="eidtForm.info.period_num"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import { ref, reactive } from "vue";
    import { ElMessage, ElMessageBox } from "element-plus";
    import { barcodeList, barcodeCreate, barcodeUpdate, dictBarType } from "../api/index";
    import { typeName, log } from "../utils/user"

    export default {
        name: "basetable",
        setup() {
            const statusText = ["禁用", "启用"]
            const typeNames = typeName();

            let typeText = {};
            Object.keys(typeNames).forEach(k => {
                typeText[typeNames[k][0]] = typeNames[k][1]
            })
            log("typeText", typeText);

            const query = reactive({
                keywords: "",
                type: '0',
                page: 1,
                limit: 15,
            });
            const adviceTypes = ref([])
            const tableData = ref([]);
            const pageTotal = ref(0);

            // 获取表格数据
            const getData = () => {
                barcodeList(query).then((res) => {
                    if (res.status == 'ok') {
                        adviceTypes.value =  res.data.type
                        tableData.value = res.data.list.list;
                        pageTotal.value = res.data.list.pageTotal || 1;
                    } else {
                        ElMessage.error(res.msg)
                        return false;
                    }
                });
            };
            getData();

            // 查询操作
            const handleSearch = () => {
                query.page = 1;
                getData();
            };
            // 分页导航
            const handlePageChange = (val) => {
                query.page = val;
                getData();
            };

            // 删除操作
            const handleDelete = (index) => {
                // 二次确认删除
                ElMessageBox.confirm("确定要删除吗？", "提示", {
                    type: "warning",
                })
                    .then(() => {
                        ElMessage.success("删除成功");
                        tableData.value.splice(index, 1);
                    })
                    .catch(() => { });
            };
            const barTypes = ref([])
            const getTypeData = () => {
                dictBarType({}).then(res => {
                    if (res.status == 'ok') {
                        barTypes.value = res.data
                    }
                })
            };
            getTypeData()

            const getBarType = id => {
                let bartype = barTypes.find(v => v.dic_id == id);
                return bartype.dic_vlu
            }
            const periodTypes = [
                {
                    id: "1",
                    title: "长期"
                },
                {
                    id: "2",
                    title: "时间范围 "
                },
                {
                    id: "3",
                    title: "扫码次数限制"
                },
            ]
            const getPeriodType = id => {
                let periodType = periodTypes.find(v => v.id == id);
                return periodType.title
            }
            // 表格添加
            const addVisible = ref(false);
            const handleCreate = () => {
                addVisible.value = true;
            };

            let createForm = reactive({
                bar_type: "1",
                bar_val: "",
                bar_rtn1: "",
                bar_rtn2: "",
                bar_rtn3: "",
                bar_rtn4: "",
                bar_rtn5: "",
                period_type: "1",
                date: "",
                period_num: "1",
            });

            const saveCreate = () => {
                log(createForm)
                if (!createForm.bar_val) {
                    ElMessage.error('请输入条码值')
                    return false;
                }


                barcodeCreate(createForm).then(res => {
                    if (res.status == 'ok') {
                        addVisible.value = false;
                        ElMessage.success(res.msg);
                        query.pageIndex = 1;
                        getData();
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            }


            // 表格编辑时弹窗和保存
            const editVisible = ref(false);
            let eidtForm = reactive({
                id: 0,
                info: {
                    bar_type: '1',
                    period_state: '1',
                    bar_val: "",
                    bar_rtn1: "",
                    bar_rtn2: "",
                    bar_rtn3: "",
                    bar_rtn4: "",
                    bar_rtn5: "",
                    period_type: "0",
                    date: "",
                    period_num: "1",
                }
            });
            let idx = -1;
            const handleEdit = (index, row) => {
                idx = index;
                eidtForm.info.bar_type = row["bar_type"];
                eidtForm.info.period_state = row["period_state"] + '';
                eidtForm.info.bar_val = row["bar_val"];
                eidtForm.info.bar_rtn1 = row["bar_rtn1"];
                eidtForm.info.bar_rtn2 = row["bar_rtn2"];
                eidtForm.info.bar_rtn3 = row["bar_rtn3"];
                eidtForm.info.bar_rtn4 = row["bar_rtn4"];
                eidtForm.info.bar_rtn5 = row["bar_rtn5"];
                eidtForm.info.period_type = row["period_type"];
                eidtForm.info.date = [row["period_start"], row["period_end"]];
                eidtForm.info.period_num = row["period_num"];
                eidtForm.id = row["bar_id"];
                log(eidtForm)
                editVisible.value = true;
            };
            const saveEdit = () => {
                if (!eidtForm.info.bar_val) {
                    ElMessage.error('请输入条码值')
                    return false;
                }
                barcodeUpdate(eidtForm).then(res => {
                    if (res.status == 'ok') {
                        editVisible.value = false;
                        ElMessage.success(res.msg);
                        getData();
                    } else {
                        ElMessage.error(res.msg)
                    }
                })

            };
            const toggleStatus = (id, status) => {
                log("toggleStatus", id)
                let temp = {
                    id: id,
                    info: {
                        status: status
                    }
                }

                ElMessageBox.confirm("确认修改吗", "提示", {
                    type: "warning",
                })
                    .then(() => {
                        accountUpdate(temp).then(res => {
                            if (res.status == 'ok') {
                                ElMessage.success(res.msg)
                                getData();
                                return false;
                            } else {
                                ElMessage.error(res.msg)
                                return false;
                            }
                        })
                    })
                    .catch(() => { });


            }
            const getAdviceType = id => {
                let advice = adviceTypes.value.find(v => v.dic_key == id);
                return advice ? advice.dic_vlu : id
            }
            return {
                statusText,
                typeText,

                // data
                query,
                tableData,
                pageTotal,


                handleSearch,
                handlePageChange,
                handleDelete,

                editVisible,
                eidtForm,
                handleEdit,
                saveEdit,

                createForm,
                addVisible,
                handleCreate,
                saveCreate,

                toggleStatus,

                periodTypes,
                barTypes,
                getBarType,
                getPeriodType,
                getAdviceType
            };
        },
    };
</script>

<style scoped>
    .handle-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }

    .m-radio {
        margin: 12px;
    }
</style>